<template>
  <!-- 回复对话框 -->
  <el-dialog
    title=" "
    :visible.sync="dialogSession"
    :modal="false"
    :close-on-click-modal="false"
    class="dialog-style"
    width="520px"
    append-to-body
    @close="dialogClose"
  >
    <span slot="title" class="dialog-title"> 与{{ customer.name }}的对话 </span>
    <div ref="mianscroll" class="main">
      <div v-if="isLoadmore" class="flexcc mb-2 mt-1" @click="loadmore">
        点击查看历史消息
      </div>

      <div v-for="(item, index) in infoList" :key="index" class="item">
        <!-- 对方 -->
        <div v-if="item.receivedCustomerId === 0" class="user-left-box">
          <img :src="item.customerAvatar || defaultAvatar" class="avatar" />
          <div class="content-box">
            <div class="name-box">
              <span class="name">{{ item.customerName || defaultName }}</span>
              <span class="time">{{ parseTime(item.createTime) }}</span>
            </div>
            <span class="content" v-html="item.content"></span>
          </div>
        </div>
        <!-- 自己 -->
        <div v-if="item.sendingCustomerId === 0" class="user-right-box">
          <div class="content-box">
            <div class="name-box">
              <span class="name">{{ item.customerName || defaultName }}</span>
              <span class="time">{{ parseTime(item.createTime) }}</span>
            </div>
            <span
              :class="['content', `state-${item.state}`]"
              v-html="item.content"
            ></span>
          </div>
          <img :src="item.customerAvatar || defaultAvatar" class="avatar" />
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-input
        v-model="content"
        type="textarea"
        placeholder="请输入"
        :rows="4"
        :autosize="{ minRows: 4, maxRows: 4 }"
        @keyup.enter.native="carriageReturn($event)"
        @keydown.native="keydown"
      />
      <el-button class="btn-nor" @click="sendMessage"> 发送 </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getSession,
  addSession,
  getUnreadInfoListApi,
  getSendingUnreadInfoListApi,
} from "@/api/system/session";

export default {
  name: "Dialogue",
  components: {},
  model: {
    prop: "modelvalue",
    event: "change",
  },
  props: {
    modelvalue: {
      type: Boolean,
      default: false,
    },
    customer: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      dialogSession: this.modelvalue,
      defaultAvatar: require("../../../assets/images/icon_touxiang_01.png"), // 系统默认头像
      defaultName: "船队经理网",
      infoList: [],
      content: "",
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      isLoadmore: true,
      timerInfo: null,
    };
  },
  created() {
    this.getInfo();
    this.timerInfo = setInterval(() => {
      this.getUnreadInfoList();
      this.getSendingUnreadInfoList();
    }, 1000 * 10);
  },
  destroyed() {
    if (this.timerInfo) {
      clearInterval(this.timerInfo);
      this.timerInfo = null;
    }
  },
  watch: {
    customer: {
      handler() {
        this.resetData();
        this.getInfo();
      },
      deep: true,
    },
  },
  methods: {
    // 重置
    resetData() {
      this.isLoadmore = true;
      this.page.pageNum = 1;
      this.infoList = [];
      this.content = "";
    },
    loadmore() {
      this.page.pageNum++;
      this.getInfo("top");
    },
    getInfo(type = "bottom") {
      getSession(this.customer.id, this.page).then((res) => {
        if (res.code === 200) {
          this.infoList = [...res.rows.reverse(), ...this.infoList];
          this.total = res.total;

          this.scrollTo(type);

          if (this.infoList.length >= this.total) {
            this.isLoadmore = false;
          }
        }
      });
    },
    scrollTo(type) {
      this.$nextTick(() => {
        const scrollEl = this.$refs.mianscroll;

        const obj = {
          top: 0,
          bottom: scrollEl.scrollHeight,
        };
        scrollEl.scrollTo({
          top: obj[type],
          behavior: "smooth",
        });
      });
    },
    // 按下回车发送消息
    carriageReturn() {
      const e = window.event || arguments[0];
      if (
        (e.key === "Enter" || e.code === "Enter" || e.keyCode === 13) &&
        !e.shiftKey
      ) {
        e.returnValue = false;
        this.sendMessage();
        return false;
      }
    },
    // shift+回车换行
    keydown(e) {
      if (!e.shiftKey && e.keyCode === 13) {
        e.cancelBubble = true; // ie阻止冒泡行为
        e.stopPropagation(); // Firefox阻止冒泡行为
        e.preventDefault(); // 取消事件的默认动作*换行
      }
    },
    // 发送消息
    sendMessage() {
      const sendParams = {
        pageNum: 1,
        pageSize: 10,
        sendingCustomerId: 0,
        receivedCustomerId: this.customer.id,
        content: this.content,
      };
      if (sendParams.content.replace(/(^\s*)|(\s*$)/g, "") == "") {
        this.$message.warning("不能发送空白消息！");
        return;
      }
      addSession(sendParams).then(async (res) => {
        const {
          data: { id, createTime, sendingCustomerId },
        } = res;
        if (res.code === 200) {
          await this.getUnreadInfoList();
          this.infoList.push({
            customerAvatar: this.defaultAvatar,
            customerName: this.defaultName,
            content: this.content,
            createTime,
            id,
            sendingCustomerId,
            state: "0",
          });
          this.content = "";
          this.scrollTo("bottom");
        }
      });
    },

    // 获取未读会话数据
    async getUnreadInfoList() {
      await getUnreadInfoListApi(null, {
        receivedCustomerId: "0",
        sendingCustomerId: this.customer.id,
      }).then(({ data }) => {
        if (data.length) {
          this.infoList = [...this.infoList, ...data.reverse()];
          this.scrollTo("bottom");
        }
      });
    },

    // 查自己发的消息的已读状态
    getSendingUnreadInfoList() {
      getSendingUnreadInfoListApi(null, {
        receivedCustomerId: this.customer.id,
        sendingCustomerId: "0",
      }).then(({ data }) => {
        if (data.length) {
          const ids = data.map((d) => d.id);
          this.infoList.forEach((item) => {
            item.state = ids.includes(item.id) ? "0" : "1";
          });
        } else {
          this.infoList.forEach((item) => {
            item.state = "1"; // 状态(未读0 已读1)
          });
        }
      });
    },
    // 关闭弹窗
    dialogClose() {
      this.$emit("change", false);
    },
  },
};
</script>

<style lang="scss" scoped>
// 自定义弹窗样式
.dialog-style {
  pointer-events: none;
  ::v-deep .el-dialog {
    pointer-events: auto;
  }
  ::v-deep .el-dialog__header {
    border-bottom: 1px solid #e6ebf5;
  }
  .main {
    height: 400px;
    overflow-y: auto;
    border-radius: 4px;
    &::-webkit-scrollbar {
      width: 5px;
      height: 5px;
    }
    &::-webkit-scrollbar-track {
      background: #eaebec;
    }
    &::-webkit-scrollbar-thumb {
      border-radius: 3px;
      background: #c1c1c1;
    }

    .item {
      // background: #fff;
      padding: 18px;
      border-radius: 4px;
      .user-left-box {
        display: flex;
        justify-content: start;
        align-items: center;
        height: 80px;
        .avatar {
          border-radius: 50%;
          width: 50px;
          height: 50px;
        }
        .content-box {
          margin-left: 10px;
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          .name-box {
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: flex-start;

            .name {
              color: #252628;
            }
            .time {
              color: #9d9fa5;
              font-size: 12px;
            }
          }
          .content {
            // margin-top: 10px;
            background-color: #fff;
            display: inline-block;
            border-radius: 4px;
            color: #252628;
            padding: 10px;
            white-space: pre-line;
            max-width: 250px;
          }
        }
      }
      .user-right-box {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height: 80px;
        .avatar {
          border-radius: 50%;
          width: 50px;
          height: 50px;
        }
        .content-box {
          margin-right: 10px;
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          .name-box {
            display: flex;
            justify-content: flex-start;
            align-items: flex-end;
            flex-direction: column;
            .name {
              color: #252628;
            }
            .time {
              color: #9d9fa5;
              font-size: 12px;
            }
          }
          .content {
            // margin-top: 10px;
            display: inline-block;
            background-color: #10ecec;
            border-radius: 4px;
            color: #252628;
            padding: 10px;
            white-space: pre;
            max-width: 250px;
            white-space: normal;

            position: relative;
            &::after {
              content: "";
              display: block;
              position: absolute;
              left: -30px;
              top: 50%;
              width: 20px;
              height: 20px;
              transform: translateY(-50%);
            }
            &.state-0::after {
              background: url("~@/assets/images/icon_weidu.png") no-repeat
                center;
            }
            &.state-1::after {
              background: url("~@/assets/images/icon_yidu.png") no-repeat center;
            }
          }
        }
      }
    }
  }
  ::v-deep .dialog-footer {
    display: flex;
    justify-content: space-around;
    align-items: flex-start;
    .el-button {
      min-width: 120px;
      height: 36px;
      border-radius: 4px;
      border-color: #ca2a02;
      color: #ca2a02;
      padding: 0 10px;
      margin-left: 15px;
      &.btn-style {
        color: #fff;
        &:hover {
          color: #ca2a02;
        }
      }
      &.btn-nor {
        background-color: #ca2a02;
        color: #fff;
        // &:hover {
        //   background-color: #fff;
        //   color: #4584fc;
        // }
      }
      &.el-button--text {
        border: 0;
      }
    }
  }

  ::v-deep .dialog-title {
    color: #e6ebf5;
    font-size: 16px;
  }

  ::v-deep .el-dialog__header {
    background-color: #29333d;
    border-bottom: 1px solid #e6ebf5;
  }
  ::v-deep .el-dialog__body {
    background: #f5f5f5;
    padding: 10px;
  }
}
</style>
